/*
 * =====================================================================================
 *
 *       Filename:  subscribe.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年06月03日 08时57分46秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <fcntl.h>

const char *server_path = "/home/kylin/server.unix";

int subscribe_init()
{
    /* 订阅 */
    unlink(server_path);
    int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if(fd < 0) {
        perror("socket()");
        return -1;
    }
    struct sockaddr_un server_un;
    socklen_t server_len = sizeof(server_un);
    memset(&server_un, 0, sizeof(server_un));
    server_un.sun_family = AF_LOCAL;
    strncpy(server_un.sun_path, server_path, sizeof(server_un.sun_path) - 1);

    if(bind(fd, (struct sockaddr *)&server_un, server_len) < 0) {
        perror("bind()");
        close(fd);
        return -1;
    }
    if(listen(fd, 20) < 0) {
        perror("listen()");
        close(fd);
        return -1;
    }
    return fd;
}

int main(int argc, char **argv)
{
    int fd = subscribe_init();
    if(fd < 0) {
        return -1;
    }
    struct sockaddr_un client_un;
    socklen_t client_len;
    while(1) {
        char buff[1024] = {0};
        int ret = read(fd, buff, sizeof(buff) - 1, 0,
                           (struct sockaddr*)&client_un, &client_len);
        if(ret < 0) {
            perror("recvfrom()");
            continue;
        }
        //printf("client: %s, send[%s]\n", client_un.sun_path, buff);
        ret = sendto(fd, buff, ret, 0, 
                         (struct sockaddr*)&client_un, client_len);
        if(ret < 0) {
            perror("sendto()");
        }
    }
    return 0;
}


